package com.fernfx.xingtan.view.dialog;


import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.fernfx.xingtan.R;

/**
 * Created by wulei on 2017/7/7.
 *  加载框
 */
public class LoadingDialog extends Dialog {

    Dialog mDialog;

    public LoadingDialog(@NonNull Context context) {
        super(context);
        mDialog = new Dialog(context, R.style.dialog_style);
        mDialog.setContentView(initView(context));
    }

    private void showDialog() {
        if (null != mDialog && !mDialog.isShowing()) {
            mDialog.show();
        }
    }

    private void hideDialog() {
        if (null != mDialog) {
            if (mDialog.isShowing()) {
                mDialog.dismiss();
            }
            mDialog = null;
        }
    }

    private View initView(Context context) {
        ProgressBar pb = new ProgressBar(context);
        RelativeLayout container = new RelativeLayout(context);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);
        container.addView(pb, lp);
        return container;
    }

    static LoadingDialog sDialog;

    static LoadingDialog getInstance(Context context) {
        if (null == sDialog && null != context) {
            sDialog = new LoadingDialog(context);
        }
        return sDialog;
    }

    @Override
    public void show() {
        if (null != sDialog && !sDialog.isShowing()) {
            sDialog.showDialog();
        }
    }

    @Override
    public void hide() {
        if (null != sDialog || sDialog.isShowing()) {
            sDialog.hideDialog();
            sDialog = null;
        }
    }

    public static void show(Context context) {
        if (null != context) {
            synchronized (LoadingDialog.class) {
                LoadingDialog dialog = getInstance(context);
                if (null != dialog && !dialog.isShowing()) {
                    synchronized (LoadingDialog.class) {
                        if (null != context) {
                            dialog.show();
                        }
                    }
                }
            }
        }
    }

    public static void hide(Context context) {
        if (null != context) {
            synchronized (LoadingDialog.class) {
                LoadingDialog dialog = getInstance(context);
                if (null != dialog || dialog.isShowing()) {
                    dialog.hide();
                }
            }
        }
    }
}

